<?php

/**
 * Description of database
 *
 * @author GHoogendoorn
 * @version 0.3
 *
 * Version history:
 * 0.1  GHoogendoorn    Initial version
 * 0.2  GHoogendoorn    Added create database.
 */

require_once '/classes/Robotinformatie.php'; 
require_once '/classes/Gebruiker.php';
require_once '/../defs/DbConstants.php';


class Database {
    
    private     $connection;         //The MySQL database connection
    private     $query_result;
    private     $errors;
    private     $object;
    
    public function __construct(){

    /* Make connection to database */
      $this->connection = mysql_connect(DB_SERVER, DB_USER, DB_PASS, TRUE /* New link */) or die(mysql_error());
      if (! $this->connectDatabase() ){
          // Check db existance (Firsth time create)
          if ( mysql_errno() == 1049 ){
              if ($this->createDatabase()){

                  // If still error just stop
                  $this->connectDatabase() or die(mysql_error());
              }
          } else {
              
               die(mysql_error());
          }
      }      
//      echo "<br />". __FILE__ . ' ' . __LINE__ . ' '. "<strong>OPENED DB #". $this->connection ."</strong><br />";

     
//    $this->errors = new Error();
  
    }
    
    /**
     *
     * @return string  '' | mysqlerrno()-mysql error txt [query]
     */
    public function getDbError(){
        if (mysql_errno()){
            return mysql_errno(). '-'. mysql_error(). " [$query]";
        }
        return '';
    }

    /**
     *
     * The function checks the mysql error.
     * If found an error is triggered.
     * @param string $query
     * @return bool FALSE (Ok) or TRUE The error array is set, and should be checked.
     */
    public function checkDbErrors($query){
        if (mysql_errno()) {
            
            switch( mysql_errno()){
                case 1062:
                    $this->errors->setError( TXT_ERROR_DUPLICATE_ENTRY );
                    break;

                default:
                    $error = "MySQL error ".mysql_errno().": ".
                        mysql_error()."\n<br>".TXT_ERROR_EXECUTING ."<br>\n$query\n<br>";
                    $this->errors->setError($error);
                    break;
            }

            return TRUE;
       }
       return FALSE;
   }

   /**
    * query - Performs the given query on the database and
    * returns the result, which may be false, true or a
    * resource identifier.
    * @param string $query
    * @return bool TRUE if Ok | FALSE check error array
    */
   public function dbquery($query){
       
//       echo __FUNCTION__.__FILE__.__LINE__.'<br />';
//       echo '<pre>';
//       var_dump($query);
//       echo '</pre>';
       
       if( $this->isMySqlResource($this->connection)){
           
            $this->query_result = mysql_query($query, $this->connection);
                         
            return TRUE;
       }
       return FALSE;
   }

   /**
     *
     * @param array $data_array The result from a mysql_fetch_array()
     * @return array the modified input array
     */
    public function dbOutArray($data_array){

        foreach( $data_array as $field => $value ){
            if( is_numeric($value)){
                continue;
            } else if (is_string($value)){
                $data_array[$field] = $this->dbOutString($value);
            }
        }
        return $data_array;
    }


   /**
    * Get the single results from the database
    * This function also removes the database escapes.
    *
    * @return array The array contains the elements of mysql_fetch_array
    * 
    * @return FALSE No data was found.
    */
    public function dbFetchArray(){

        if (!$this->isMySqlResource($this->query_result)){
            return FALSE;
        }
        //TODO: add error check.	
        $data_array = mysql_fetch_array($this->query_result, MYSQL_ASSOC);

        if ($data_array === FALSE){
            return FALSE;
        }

        if(!mysql_errno()){
            $data_array = $this->dbOutArray($data_array);
        }
        return $data_array;
    }

    public function dbNumRows(){
        if ($this->isMySqlResource($this->query_result)){    
            return mysql_num_rows($this->query_result);
            
        } else {
             echo "DbNumRows Failed";
                 return FALSE;
        }
    }

    /**
    * Get multiple results from the database
    * This function also removes the database escapes.
    *
    * @return array The array contains an array with the row elements
    *
    * @return FALSE No succesfull query was found.
    */
    public function dbFetchAll(){

        if (!is_resource($this->query_result)){
            return FALSE;
           
        }
        $return_array = array();
        while ($row = mysql_fetch_array( $this->query_result, MYSQL_ASSOC ) ) {
           $return_array[] = $this->dbOutArray($row);
        }
        
        return $return_array;
    }
    
    public function dbGetInsertedId(){
        return mysql_insert_id($this->connection);
    }

   /**
    *
    * @param string $table MySql table name
    * @return bool TRUE if exists | False if not exists
    */
   public function dbTableExists($table){
        $query = "DESC ". $table;
        $result = $this->dbquery($query);

        if (mysql_errno()==1146){
            return FALSE;
        }
        return TRUE;
    }

    /**
     * The function escapes a string.
     *  This function should be called before storage
     *  in the database.
     *
     * @param string $string
     * @return string
     */
    public function dbInString($string) {

        if (function_exists('mysql_real_escape_string')) {
          return mysql_real_escape_string($string, $this->connection);
        } elseif (function_exists('mysql_escape_string')) {
          return mysql_escape_string($string);
        }

        return addslashes($string);
    }

    /**
     * The function removes the escapes from a database returned string.
     *  This function should be called after the database query.
     *
     * @param string $string
     * @return string
     */
    public function dbOutString($string) {
        if (is_string($string)) {
          return trim(stripslashes($string));
        }
    }

    /**
     * Just reset the query resource link
     * 
     */
    public function dbReset(){
        $this->query_result = '';
    }
    public function checkText($text, $len){
        if (    empty($text)            ||
                (!is_string($text))     ||
                (strlen($text) > $len )) {
            return FALSE;
        }
        return TRUE;
    }


    /**
     *
     * @param int $id A database Id.
     * @param string $field Datase field name
     * @return bool TRUE (ok) or FALSE  The error array is set, 
     *                                  and should be checked
     */
    public function checkId($id, $field){
         if ( !is_numeric($id)){
                          
            $this->errors->setError( TXT_ERROR_WRONG_VAR_TYPE . " [$id] ". $field);
            return FALSE;
        }
        return TRUE;

    }

    /**
     *
     * @param resource $res The resource that should be checked
     * @return bool TRUE if $res is mysql resource | FALSE any other case
     * (check error array)
     */
    public function isMySqlResource($res){
        $res_type = is_resource($res) ? get_resource_type($res) : gettype($res);

        if (strpos($res_type, 'mysql') === FALSE)
        {                    
            $this->errors->setError( 'Invalid resource type: '.$res_type);
            echo "<pre>";
            var_dump($this->errors);
            echo "</pre>";
            //Kint::trace();
            return FALSE;
        }
         
        return TRUE;
        }

    public function connectDatabase(){

        return mysql_select_db(DB_NAME, $this->connection);
    }

    public function createDatabase(){
        $query = "CREATE DATABASE ". DB_NAME;
        return $this->dbquery($query);
    }
    
    public function __destruct(){

        //echo "<br />". __FILE__ . ' ' . __LINE__ . ' '. "<strong>CLOSE DB #". $this->connection ."</strong><br />";
    }
    
    public function checkLogin($username, $password){   
        
        $gebruiker = new Gebruiker;
          $gebruiker->setUserName($username);
          $gebruiker->setPassword($password);

        
         if($this->dbquery("SELECT * FROM `gebruiker` WHERE `Username` = '".$gebruiker->getUsername()."' AND `Paswoord` = '".$gebruiker->getPassword()."'")) {
               
             // Controle of er iets gevonden is in de database
             if($this->dbNumRows() == 1){               
               foreach ($this->dbFetchall() as $key => $array) {   
                
                   
                 $gebruiker->setUserName($array['Username']);
                 $gebruiker->setPassword($array['Paswoord']);
                 $gebruiker->setEmail($array['Email']);
                 $gebruiker->setSecurity_Question($array['Secret_Question']);
                 $gebruiker->setSecurity_Answer($array['Secret_Answer']);
                 $gebruiker->setRecht_id($array['Rechten_Recht_ID']);           
    }
    
                    $this->setObject($gebruiker);

                 
             } else {
           
                 return FALSE;
             }    
                   
         } else {
             throw new Exception ("DB_ERROR_COULDNOTSELECT");
         }
          

          if (DEBUG_LVL & DEBUG_LVL_QUERY)  echo __FILE__ . ' ' . __LINE__ .': ' .$query . '<br />';
        
       
    }
        
    public function addGeregistreerdeGebruiker($username, $paswoord, $email, $secret_question, $secret_answer){
        
              if (
             
            !empty ($username)
                      
            ){ 
                  
                    $gebruiker = new Gebruiker;
       
             $gebruiker->setPassword($paswoord);
           
            $query = "INSERT INTO `robotik`.`gebruiker` (`Username`, `Paswoord`, `Email`, `Secret_Question`, `Secret_Answer`)
                        VALUES (                        
                            '" . mysql_real_escape_string($username) . "',
                            '" . mysql_real_escape_string($gebruiker->getPassword()) . "', 
                            '" . mysql_real_escape_string($email) . "',
                            '" . mysql_real_escape_string($secret_question) . "',
                            '" . mysql_real_escape_string($secret_answer) . "'
                            )";
                             
            if (DEBUG_LVL & DEBUG_LVL_QUERY)  echo __FILE__ . ' ' . __LINE__ .': ' .$query . '<br />';
            
            if (!$this->dbquery($query)){
 
               throw new Exception("DB_ERROR_NIETVERWERKT");
            }
  
         
             $gebruiker->setPassword($paswoord);
             $gebruiker->setEmail($email);
             $gebruiker->setSecurity_Question($secret_question);
             $gebruiker->setSecurity_Answer($secret_answer);
             
                $this->setObject($gebruiker);
  
        }
        else {
            
          throw new Exception("DB_ERROR_INVOERFOUT");
          return FALSE;
        }
        
    }
    
    
    // Database Functie addNieuweRobot (Van Wesley)
    
        public function addNieuweRobot($artikel_nummer, $artikel_naam, $progammeerbaar, $opvoorraad, $fabrikant_nummer){
        
              if (
             
            !empty ($artikel_nummer)
                      
            ){
           
            $query = "INSERT INTO `robotik`.`artikel` (`Artikelnummer`, `Artikel_Naam`, `Programmeerbaar`, `OpVoorraad`, `Fabrikant_Fabrikantnummer`)
                        VALUES (                        
                            '" . mysql_real_escape_string($artikel_nummer) . "',
                            '" . mysql_real_escape_string($artikel_naam) . "', 
                            '" . mysql_real_escape_string($progammeerbaar) . "',
                            '" . mysql_real_escape_string($opvoorraad) . "',
                            '" . mysql_real_escape_string($fabrikant_nummer) . "'
                            )";
            
           var_dump($query);
                             
            if (DEBUG_LVL & DEBUG_LVL_QUERY)  echo __FILE__ . ' ' . __LINE__ .': ' .$query . '<br />';
            
            if (!$this->dbquery($query)){
 
               throw new Exception("DB_ERROR_NIETVERWERKT");
            }
  
           $nieuwerobot = new Robotinformatie();
       
             $nieuwerobot->setArtikel_Nummer($artikel_nummer);
             $nieuwerobot->setArtikel_Naam($artikel_naam);
             $nieuwerobot->setProgrammeerbaar($progammeerbaar);
             $nieuwerobot->setOpvoorraad($opvoorraad);
             $nieuwerobot->setFabrikant_Nummer($fabrikant_nummer);
             
                $this->setObject($nieuwerobot);
  
        }
        else {
            
          throw new Exception("DB_ERROR_INVOERFOUT");
          return FALSE;
        }
        
    }
    
    
    // Database Functie updateNieuweRobot (Van Wesley)
    
            public function updateNieuweRobot($artikel_nummer, $artikel_naam, $progammeerbaar, $opvoorraad, $fabrikant_nummer){
        
              if (
             
            !empty ($artikel_nummer)
                      
            ){
           
            $query = "UPDATE `robotik`.`artikel` (`Artikelnummer`, `Artikel_Naam`, `Programmeerbaar`, `OpVoorraad`, `Fabrikant_Fabrikantnummer`)
                        VALUES (                        
                            '" . mysql_real_escape_string($artikel_nummer) . "',
                            '" . mysql_real_escape_string($artikel_naam) . "', 
                            '" . mysql_real_escape_string($progammeerbaar) . "',
                            '" . mysql_real_escape_string($opvoorraad) . "',
                            '" . mysql_real_escape_string($fabrikant_nummer) . "'
                            )";
                             
            if (DEBUG_LVL & DEBUG_LVL_QUERY)  echo __FILE__ . ' ' . __LINE__ .': ' .$query . '<br />';
            
            if (!$this->dbquery($query)){
 
               throw new Exception("DB_ERROR_NIETVERWERKT");
            }
  
           $nieuwerobot = new Robotinformatie();
       
             $nieuwerobot->setArtikel_Nummer($artikel_nummer);
             $nieuwerobot->setArtikel_Naam($artikel_naam);
             $nieuwerobot->setProgrammeerbaar($progammeerbaar);
             $nieuwerobot->setOpvoorraad($opvoorraad);
             $nieuwerobot->setFabrikant_Nummer($fabrikant_nummer);
             
                $this->setObject($nieuwerobot);
  
        }
        else {
            
          throw new Exception("DB_ERROR_INVOERFOUT");
          return FALSE;
        }
        
    }
    
    
    
    
    
    // Database Functie updateNieuweRobot (Van Wesley)
    
            public function deleteNieuweRobot($artikel_nummer, $artikel_naam, $progammeerbaar, $opvoorraad, $fabrikant_nummer){
        
              if (
             
            !empty ($artikel_nummer)
                      
            ){
           
            $query = "DELETE from `robotik`.`artikel` (`Artikelnummer`, `Artikel_Naam`, `Programmeerbaar`, `OpVoorraad`, `Fabrikant_Fabrikantnummer`)
                        VALUES (                        
                            '" . mysql_real_escape_string($artikel_nummer) . "',
                            '" . mysql_real_escape_string($artikel_naam) . "', 
                            '" . mysql_real_escape_string($progammeerbaar) . "',
                            '" . mysql_real_escape_string($opvoorraad) . "',
                            '" . mysql_real_escape_string($fabrikant_nummer) . "'
                            )";
                             
            if (DEBUG_LVL & DEBUG_LVL_QUERY)  echo __FILE__ . ' ' . __LINE__ .': ' .$query . '<br />';
            
            if (!$this->dbquery($query)){
 
               throw new Exception("DB_ERROR_NIETVERWERKT");
            }
  
           $nieuwerobot = new Robotinformatie();
       
             $nieuwerobot->setArtikel_Nummer($artikel_nummer);
             $nieuwerobot->setArtikel_Naam($artikel_naam);
             $nieuwerobot->setProgrammeerbaar($progammeerbaar);
             $nieuwerobot->setOpvoorraad($opvoorraad);
             $nieuwerobot->setFabrikant_Nummer($fabrikant_nummer);
             
                $this->setObject($nieuwerobot);
  
        }
        else {
            
          throw new Exception("DB_ERROR_INVOERFOUT");
          return FALSE;
        }
        
    }
    
    public function setObject($array){
        $this->object =  $array;
    }
    
    public function getObject(){
         return $this->object;
    }
    
    
    
}
?>
